package com.xw.bo.ks.service.impl;

import com.alibaba.fastjson.JSON;
import com.xw.bo.ks.client.RedisClient;
import com.xw.bo.ks.entity.AccountInfo;
import com.xw.bo.ks.entity.CompanyToken;
import com.xw.bo.ks.entity.common.RedisCommon;
import com.xw.bo.ks.service.TokenService;
import com.xw.bo.ks.util.FileUtil;
import com.xw.bo.ks.util.OkHttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.AbstractFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author： XW -> ~
 * @create： 2024/4/1 17:58
 */
@Slf4j
@Service
public class TokenServiceImpl implements TokenService {

    @Resource
    private RedisClient redisClient;

    private Map<Integer, CompanyToken> map;

    @Override
    public void init() {
        map = new HashMap<>();

        CompanyToken token = new CompanyToken();
        token.setUserId(10000);
        token.setCompanyId(1);
        token.setToken("ba0a68dd-72df-4e29-bf37-418dad3b8750");

        map.put(token.getCompanyId(),token);
        String directory = FileUtil.currentFile() + File.separator + "file" + File.separator + "token";
        try {
            List<File> fileList = findFile(directory);
            for (File file : fileList) {
                String string = FileUtil.readFileToString(file);
                readTokenFile(string);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void readTokenFile(String msg){
        try {
            CompanyToken parsedObject = JSON.parseObject(msg, CompanyToken.class);
            map.put(parsedObject.getCompanyId(),parsedObject);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public CompanyToken getToken(Integer companyId) {
        if (map.containsKey(companyId)) {
            return map.get(companyId);
        }
        return null;
    }

    @Override
    public void refreshToken(Integer userId) {
        setTokenByHttp(userId);
    }


    /**
     * 为了token统一，本地不刷新token,内网可以刷新token
     *
     * @return
     */
    private void setTokenByHttp(Integer userId) {

        AccountInfo accountInfo = getAccountInfoById(userId);


        CompanyToken companyToken = new CompanyToken();
        companyToken.setCompanyId(accountInfo.getCompanyId());
        companyToken.setUserId(accountInfo.getId());
        companyToken.setToken(accountInfo.getToken());

        map.put(accountInfo.getCompanyId(),companyToken);

    }


    /**
     * 通过id找到账号信息
     *
     * @param accountId 账号id
     * @return 账号信息
     */
    public AccountInfo getAccountInfoById(Integer accountId) {
        if (accountId == null || accountId == 0){
            return null;
        }
        List<Integer> accountIdList = new ArrayList<>();
        accountIdList.add(accountId);
        Map<Integer, AccountInfo> accountInfoMap = getAccountInfoMapByIdList(accountIdList);
        if (accountInfoMap.containsKey(accountId)) {
            AccountInfo accountInfo = accountInfoMap.get(accountId);
            if (accountInfo.getId() == null && StringUtils.isEmpty(accountInfo.getNickname())){
                return null;
            }
            return accountInfo;
        }

        return null;
    }

    /**
     * 给一堆账号id，去redis中取一堆账号的详细信息
     *
     * @param accountId 账号id
     * @return 账号信息集合
     */
    public Map<Integer, AccountInfo> getAccountInfoMapByIdList(List<Integer> accountId) {

        List<String> keys = new ArrayList<>();
        for (Integer id : accountId) {
            keys.add(String.format(RedisCommon.USER_INFO_KEY, id));
        }

        Map<String, AccountInfo> mhget = redisClient.mhget(keys);
        Map<Integer, AccountInfo> accountInfoMap = new HashMap<>();

        accountId.forEach(a -> {
            String key = String.format(RedisCommon.USER_INFO_KEY, a);
            if (mhget.containsKey(key)) {
                accountInfoMap.put(a, mhget.get(key));
            }
        });

        return accountInfoMap;
    }

    private List<File> findFile(String directory) throws IOException {

//        return FileUtil.listFiles(new File(directory), false, new AbstractFileFilter() {
//            @Override
//            public boolean accept(File file) {
//                return false;
//            }
//        }, new AbstractFileFilter() {
//            @Override
//            public boolean accept(File file) {
//                return false;
//            }
//        });
        return new ArrayList<>();
    }

}
